// 光标管理工具
const CursorManager = {
    // 保存当前光标位置
    savePosition: (editor) => {
        const selection = window.getSelection();
        if (!selection.rangeCount) return null;

        const range = selection.getRangeAt(0);
        const preCaretRange = range.cloneRange();
        preCaretRange.selectNodeContents(editor);
        preCaretRange.setEnd(range.startContainer, range.startOffset);

        return {
            startOffset: range.startOffset,
            startContainer: range.startContainer,
            charsBefore: preCaretRange.toString().length
        };
    },

    // 恢复光标位置
    restorePosition: (editor, savedPos) => {
        if (!savedPos) return;

        const textNodes = [];
        const walker = document.createTreeWalker(
            editor,
            NodeFilter.SHOW_TEXT,
            null,
            false
        );

        let charCount = 0;
        let foundNode = null;

        while (walker.nextNode()) {
            const node = walker.currentNode;
            textNodes.push(node);

            if (charCount + node.length >= savedPos.charsBefore) {
                foundNode = node;
                break;
            }
            charCount += node.length;
        }

        const selection = window.getSelection();
        const range = document.createRange();

        if (foundNode) {
            range.setStart(foundNode, savedPos.charsBefore - charCount);
        } else if (textNodes.length) {
            // 回退到最后一个文本节点
            const lastNode = textNodes[textNodes.length - 1];
            range.setStart(lastNode, lastNode.length);
        } else {
            // 回退到编辑器末尾
            range.selectNodeContents(editor);
            range.collapse(false);
        }

        range.collapse(true);
        selection.removeAllRanges();
        selection.addRange(range);
    }
};

export default CursorManager;